package com.cet.algorithm.二叉树.完全二叉树节点数;

/**
 * @program: algorithm
 * @description: 完全二叉树节点树
 * @author: 陈恩涛
 * @create: 2022-07-20 14:35
 **/
public class LC222 {

    public static void main(String[] args) {

    }

    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        final int leftDepth = getDepth(root.left);
        final int rightDepth = getDepth(root.right);
        if (leftDepth == rightDepth) {
            // 左子树为满二叉树
            // 1 << leftDepth 为 当前节点 + 左子树节点的和
            return (1 << leftDepth) + countNodes(root.right);
        } else {
            // 右子树为满二叉树
            return countNodes(root.left) + (1 << rightDepth);
        }
    }

    private int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int depth = 0;
        while (root != null) {
            root = root.left;
            depth++;
        }
        return depth;
    }
}
